import os.path
from base64 import b64encode

from rdflib import ConjunctiveGraph
from rdflib import URIRef

cache_dir = None

def cacheFile(uri):
    return os.path.join(cache_dir, b64encode(uri.encode('utf-8')).decode()) if cache_dir else None

def isCached(uri):
    return os.path.isfile(cacheFile(uri)) if cache_dir else None

def uriSource(uri):
    return cacheFile(uri) if cache_dir and isCached(uri) else uri


def foaf_uriref(name):
    return URIRef('http://xmlns.com/foaf/0.1/{}'.format(name))


_FOAF_CLASSES = """Agent Person OnlineAccount""".split()
class FoafGraph(ConjunctiveGraph):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name in _FOAF_CLASSES:
            setattr(self, "_get_%ss" % name, self._make_class_getter(name))
            setattr(FoafGraph, "%ss" % name, property(self._make_property_class_getter(name)))

    ''' maybe these will actually generate a class instance in the future '''
    def _make_class_getter(self, name):
        def method():
            return [str(x) for x in self.subjects(predicate=URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), object=foaf_uriref(name))]
        return method

    def _make_property_class_getter(self, name):
        def method(self):
            return [str(x) for x in self.subjects(predicate=URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), object=foaf_uriref(name))]
        return method
